<?php
namespace TwOauth;

use ArrayObject;

class Recorder extends ArrayObject
{

    const KEY_SESSION = 'tw:oauth:sdk';

    public function __construct(Array $data = array())
    {
        if (! count($data) && session()->has(self::KEY_SESSION)) {
            $data = session()->get(self::KEY_SESSION);
        }
        parent::__construct($data, ArrayObject::ARRAY_AS_PROPS);
    }

    public function write($key, $value)
    {
        $this->offsetSet($key, $value);
        return $this;
    }

    public function read($key)
    {
        return $this->offsetExists($key) ? $this->offsetGet($key) : null;
    }

    /**
     * 初始化数据
     *
     * @param array $data            
     * @return \TwOauth\Recorder
     */
    public function initData(Array $data = array())
    {
        foreach ($this->getArrayCopy() as $key => $value) {
            $this->offsetUnset($key);
        }
        foreach ($data as $key => $value) {
            $this->offsetSet($key, $value);
        }
        return $this;
    }

    /**
     * 主动同步到session
     */
    public function save()
    {
        if ($this->count()) {
            // 保存数据到session
            session()->put(self::KEY_SESSION, $this->getArrayCopy());
        } else {
            // 删除数据到session
            session()->forget(self::KEY_SESSION);
        }
    }

    public function __destruct()
    {
        $this->save();
    }
}
